/*
 * Copyright 2016 Wealth Inc. All rights reserved.
 */
 package com.wealth.commodity.service.impl;

import iaas.enums.StatusEnum;
import iaas.enums.YesOrNoEnum;
import iaas.persistence.DynamicSpecifications;
import iaas.persistence.SearchFilter;
import iaas.persistence.SearchFilter.Operator;
import iaas.service.impl.BaseServiceImpl;
import iaas.web.JqGridRequest;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Lists;
import com.wealth.bbs.entity.Topic;
import com.wealth.bbs.vo.TopicVO;
import com.wealth.commodity.entity.Category;
import com.wealth.commodity.entity.Goods;
import com.wealth.commodity.entity.GoodsPic;
import com.wealth.commodity.entity.GoodsVirtual;
import com.wealth.commodity.entity.Purrestrictions;
import com.wealth.commodity.enums.GoodsStatusEnum;
import com.wealth.commodity.repository.GoodsDao;
import com.wealth.commodity.service.ICommentService;
import com.wealth.commodity.service.IGoodsPicService;
import com.wealth.commodity.service.IGoodsService;
import com.wealth.commodity.service.IGoodsVirtualService;
import com.wealth.commodity.service.IPurrestrictionsService;
import com.wealth.commodity.vo.FloorGoodsVO;
import com.wealth.commodity.vo.GoodsVO;
import com.wealth.merchant.entity.Merchant;
import com.wealth.merchant.enums.MarketEnum;
import com.wealth.merchant.enums.XTCEnum;
import com.wealth.merchant.service.IMerchantService;
import com.wealth.order.entity.Order;
import com.wealth.order.entity.OrderItem;
import com.wealth.order.entity.OrderPlat;
import com.wealth.order.repository.OrderItemDao;
import com.wealth.system.entity.User;
import com.wealth.system.service.ShiroUser;

/**
 * @author chan
 * @version 1.0
 * @since 1.0
 */
 
@Component
public class GoodsServiceImpl extends BaseServiceImpl<Goods> implements IGoodsService{

	@Autowired
	private IGoodsPicService goodsPicService;
	@Autowired
	private IMerchantService merchantService;
	@Autowired
	private IGoodsVirtualService goodsVirtualService;
	@Autowired
	private ICommentService commentService;
	
	@Autowired
	private GoodsDao goodsDao;
	@Autowired
	private IPurrestrictionsService purrestrictionsService;
	@Autowired
	private OrderItemDao orderItemDao;
	@PersistenceContext
 	private EntityManager em;
	/** ---------------- 后台 ---------------- */
	
	/** 保存商品 */
	@Override
	@Transactional
	public void saveGoods(Goods goods)  throws Exception{
		//商户信息
		User user = ShiroUser.getInstance().getUser();
		Merchant merchant = merchantService.getMerchantByUserId(user.getId());

		//虚拟商品
		if(goods.getIsVirtual()==1){
			GoodsVirtual goodsVirtual = goodsVirtualService.saveGoodsVirtual(goods.getGoodsVirtual());
			goods.setGoodsVirtual(goodsVirtual);
		}else{
			goods.setGoodsVirtual(null);
		}
		//商品
		if(goods.getActivity().getId()==null){
			goods.setActivity(null); 
		}
		if(goods.getIsInventory()==0){
			goods.setRemain(0);
		}
		goods.setMerchant(merchant);
		
		goods.setStatus(StatusEnum.NORMAL.getValue());
		
		goods.setSales(0);
		goods.setCreateTime(new Date());
		goodsDao.save(goods);
		
		//商品图片
		List<GoodsPic> picList = goods.getGoodsPicList();
		for (GoodsPic pic : picList) {
			pic.setGoods(goods);
			goodsPicService.save(pic);
		}
		
	}

	/** 修改商品 */
	@Override
	@Transactional
	public void updateGoods(Goods goods) throws Exception {
		//商品
		if(goods.getActivity().getId()==null){
			goods.setActivity(null);
		}
		if(goods.getIsVirtual()==0){
			goods.setGoodsVirtual(null);
		}
		if(goods.getIsInventory()==0){
			goods.setRemain(0);
		}
		goodsDao.save(goods);
		
		
		//删除商品之前关联的图片
		deletePics(goods.getId());
		
		//页面传入的商品图片,新增
		List<GoodsPic> picList = goods.getGoodsPicList();
		for (GoodsPic pic : picList) {
			if (pic.getId() == null && pic.getPicurl()!=null) {
				pic.setGoods(goods);
				goodsPicService.save(pic);
			}
		}
		
		//虚拟商品
		if(goods.getIsVirtual()==1){
			goodsVirtualService.updateGoodsVirtual(goods.getGoodsVirtual());
		}
		
	}
	
	/** 批量保存商品 */
	@Override
	public boolean importFile(MultipartFile file, Long categoryid) throws Exception {
		try {
			/** -------- 读取文件 -------- */
			//工作簿
			Workbook workbook = WorkbookFactory.create(file.getInputStream());		
			//工作表
			Sheet sheet =workbook.getSheetAt(0); 					
			//总行
			int rows = sheet.getLastRowNum();																
			//遍历行, r=0 对应说明文字
			List<Goods> goodsList = Lists.newArrayList(); 
			for (int r = 1; r<=rows; r++) {
				Row row  = sheet.getRow(r);
				if(row==null){
					continue;
				}
				//总列
				int cells = row.getLastCellNum();			
				//商品
				Goods goods = new Goods();
				//遍历每一列
				for (int col = 0; col<cells; col++) {
					//设置每一列为字符串
					if(row.getCell(col)!=null){
						row.getCell(col).setCellType(Cell.CELL_TYPE_STRING);
					}
				}
				
				goods.setName(row.getCell(0)==null?"":row.getCell(0).toString());
				goods.setTitle(row.getCell(1)==null?"":row.getCell(1).toString());
				goods.setOriginalPrice(row.getCell(2)==null?0d:Double.parseDouble(row.getCell(2).toString()));
				goods.setPromotionPrice(row.getCell(3)==null?0d:Double.parseDouble(row.getCell(3).toString()));
				goods.setIsVirtual(0);
				goods.setPrice(goods.getPromotionPrice());
				goods.setCategory(new Category(categoryid));
				goods.setIsCheap(0);
				goods.setIsDiscount(0);
				goods.setIsFullcut(0);
				goods.setIsInventory(0);
				// 名字为空不能存入
				if(!goods.getName().equals("")){
				goodsList.add(goods);
				}	
			}
			workbook.close();

			/** -------- 处理业务逻辑 -------- */
			//去重复,检验（未做）-->excel限制单元格
			
			//如果手机号存在于数据库中，更新数据
			for (int i=0; i<goodsList.size(); i++) {
				//保存
				saveGoods(goodsList.get(i));
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} 
	}
	
	/** 查询商品  商户*/
	public Page<Goods> getAllByMerchantId(Long merchantid, JqGridRequest request) throws Exception{
		//创建分页请求.
		int pageNumber = request.getPage();
		int pageSize = request.getRows();
		String sortType = StringUtils.isEmpty(request.getSidx())?"id":request.getSidx();
		String sortDirection = StringUtils.isEmpty(request.getSord())?"desc":request.getSord();
		Direction direction = sortDirection.equals("desc")?Direction.DESC:Direction.ASC;
		Sort sort = new Sort(direction, sortType);
		PageRequest pageRequest = new PageRequest(pageNumber - 1, pageSize, sort);

		//创建动态查询条件组合.
		Collection<SearchFilter> filters = SearchFilter.parse(request);
		filters.add(new SearchFilter("status", Operator.NE, StatusEnum.DELETE.getValue()));
		filters.add(new SearchFilter("merchant.id", Operator.EQ, merchantid));
		Specification<Goods> spec = DynamicSpecifications.bySearchFilter(filters, Goods.class);
		return goodsDao.findAll(spec, pageRequest);
	}
	
	/**
	 * 检查商品库存
	 * true表示成功
	 * false表示失败
	 */
	@Override
	@Transactional
	public boolean checkInventory(Goods goods, Integer amount) throws Exception {
			if(goods.getRemain()<=0){
				return false;
			}
		return true;
	}
	
	/**
	 * 减少商品库存
	 * true表示成功
	 * false表示失败
	 */
	@Override
	@Transactional
	public boolean decreaseRemain(Long id, Integer amount) throws Exception {
		//编辑商品
		Goods temp = goodsDao.findOne(id);
		//不符合减少库存的条件,超出库存，库存已为0
		if(amount>temp.getRemain()){
			return false;
		}
		temp.setRemain(temp.getRemain()-amount);
		goodsDao.save(temp);
		return true;
	}
	
	/**
	 * 增加商品销量
	 */
	@Override
	@Transactional
	public void increaseSales(Long id, Integer amount) throws Exception{
		//编辑商品
		Goods temp = goodsDao.findOne(id);
		
		if(temp.getSales()==null){
			temp.setSales(0+amount);
		}else{
			temp.setSales(temp.getSales()+amount);
		}
		goodsDao.save(temp);
	}


	/** ---------------- 微信端 ---------------- */
	
	/**
	 *  查询某分类下状态为上架的商品
	 */
	public List<GoodsVO>  getPag (Long categoryId , Integer status,Long marketId) throws Exception {
		List<GoodsVO> list=new ArrayList<GoodsVO>();
		//查询商品
		List<Goods> goods=goodsDao.getPag(categoryId, status, marketId);
		for (int i = 0; i < goods.size(); i++) {
			GoodsVO vo=new GoodsVO();
			vo.setGoods(goods.get(i));
			vo.setScore(commentService.getAvgScore(goods.get(i).getId()));
			list.add(vo);
		}
		return list;
	}
	
	
	
	
	/**
	 *  加载更多
	 */
	@Override
	public List<GoodsVO> getPagMore(Long id, Long categoryId, Integer status,Long marketId) throws Exception{
		
		List<GoodsVO> list=new ArrayList<GoodsVO>();
		//查询商品
		List<Goods> goods=goodsDao.getPagMore(id, categoryId, status, marketId);
		for (int i = 0; i < goods.size(); i++) {
			GoodsVO vo=new GoodsVO();
			vo.setGoods(goods.get(i));
			vo.setScore(commentService.getAvgScore(goods.get(i).getId()));
			list.add(vo);
		}
		return list;
	}

	/** 
	 * 查询商品 市场+状态
	 * 按销量排序
	 * 微信端 -> 惠生活首页
	 */
	@Override
	public List<Goods> getGoodsByMerchantMarketIdAndStatus(Long marketid, Integer status) throws Exception{
		return goodsDao.findByMerchantMarketIdAndStatusOrderBySalesDesc(marketid, status);
	}

	/**
	 * 查询商品 特价
	 * 微信端 -> 首页
	 */
	@Override
	public List<Goods> getGoodsByMerchantIdAndStatus(Long merchantid, Integer status) throws Exception{
		return goodsDao.findByMerchantIdAndStatusOrderBySalesDesc(merchantid, status);
	}

	/** 
	 * 查询商品 商户+状态 
	 * 微信端 -> 惠生活商户详情
	 */
	@Override
	public List<Goods> getCheapGoodsList(Long corpid, Integer index, Integer offset) throws Exception {
		
		/** ---- 分页查询 ---*/
		//创建分页请求.
		Sort sort = new Sort(Direction.DESC,"id");
		PageRequest pageRequest = new PageRequest(0, offset, sort);
		//创建动态查询条件组合.
		Collection<SearchFilter> filters = new ArrayList<SearchFilter>();
		filters.add(new SearchFilter("status", Operator.EQ,  GoodsStatusEnum.UP.getValue() ));
		filters.add(new SearchFilter("isCheap", Operator.EQ, YesOrNoEnum.YES.getValue()));
		List<Long> marketIds = Lists.newArrayList(2l,3l);//本地购和品牌购 ，涉及rmb
		filters.add(new SearchFilter("merchant.market.id", Operator.IN, marketIds));
		filters.add(new SearchFilter("merchant.status", Operator.EQ, StatusEnum.NORMAL.getValue()));
		filters.add(new SearchFilter("merchant.type", Operator.EQ, 0));//品牌购非活动商户
		if(index!=-1){
			filters.add(new SearchFilter("id", Operator.LT, index));
		}
		Specification<Goods> spec = DynamicSpecifications.bySearchFilter(filters, Goods.class);
		Page<Goods> page = goodsDao.findAll(spec,pageRequest);
		List<Goods> goodsList=page.getContent();
		return goodsList;
	}

	/**
	 *  商品详情
	 */
	@Override
	public GoodsVO getGoods(Long goodsId) throws Exception {
		
		Goods goods=goodsDao.findOne(goodsId);
		
		GoodsVO goodsVO=new GoodsVO();
		goodsVO.setGoods(goods);
		goodsVO.setScore(commentService.getAvgScore(goods.getId())); //分数
		goodsVO.setCommentNum(commentService.getCommentNum(goodsId));//评价次数
		goodsVO.setComments(commentService.getLatestComment(goodsId, 3));//商品评价信息
		
		return goodsVO;
	}

	@Override
	public Page<Goods> getGoodsApi(Integer sortno, Integer offset, Goods goods)
			throws Exception {
		 
		List<SearchFilter> filters = new ArrayList<SearchFilter>();
		 
		filters.add(new SearchFilter("id", SearchFilter.Operator.GT,sortno)); 
		 //上架
		filters.add(new SearchFilter("status", SearchFilter.Operator.EQ,GoodsStatusEnum.UP.getValue()));
		 
		filters.add(new SearchFilter("merchant.market.id", SearchFilter.Operator.EQ,4l));
		 
		if(goods!=null){
			//产品类型   0 实物  1虚拟
			if(goods.getIsVirtual()!=null && goods.getIsVirtual()>-1){
			    filters.add(new SearchFilter("isVirtual", SearchFilter.Operator.EQ,goods.getIsVirtual())); 
			} 
			
		    //限时 和 限量
			if(goods.getLimitType()!=null){
				filters.add(new SearchFilter("limitType", SearchFilter.Operator.EQ,goods.getLimitType()));
			}
		
		}
		
		//积分城的商户
	    List<Merchant> merchantList = merchantService.findByMarketIdAndStatus(MarketEnum.SCORECITY.getValue(), StatusEnum.NORMAL.getValue());
		List<Long> merchantIds = new ArrayList<Long>();
		for (int i = 0; i < merchantList.size(); i++) {
			merchantIds.add(merchantList.get(i).getId());
		}
		if(merchantIds.size()>0){
		  filters.add(new SearchFilter("merchant.id",Operator.IN,merchantIds)); 
		}
		return get(offset, null, 0L, filters, Goods.class);
	}

	
	@Override
	public List<Goods> findTop12ByCategoryIdAndStatusOrderBySalesDesc(
			Long marketid, Integer status) {
		
		return goodsDao.findTop12ByCategoryIdAndStatusOrderBySalesDesc(marketid, status);
	}

	//模糊查询
	@Override
	public List<GoodsVO> findByStatusAndNameLike(Integer status,Long categoryId,String name,Long marketId) throws Exception{
	    List<GoodsVO> list=new ArrayList<GoodsVO>();
		
		//查询商品
		List<Goods> goods= goodsDao.findByStatusAndCategoryIdAndNameLike(status,categoryId,"%"+name+"%", marketId);
		for (int i = 0; i < goods.size(); i++) {
			GoodsVO vo=new GoodsVO();
			vo.setGoods(goods.get(i));
			vo.setScore(commentService.getAvgScore(goods.get(i).getId()));
			list.add(vo);
		}
		return list;
	}

	//查询特价商品
	@Override
	public List<Goods> findCheapGoods(Long id, Integer ischeap, Integer status) {
		return goodsDao.findCheapGoods(id, ischeap, status);
	}

	//查询折扣商品	
	@Override
	public List<Goods> findDiscountGoods(Long id, Integer ischeap,
			Integer status) {
		return goodsDao.findDiscountGoods(id, ischeap, status);
	}
	
	//查询免立减商品	
	@Override
	public List<Goods> findFullcutGoods(Long id, Integer ischeap, Integer status,Long merchantId) {
		return goodsDao.findFullcutGoods(id, ischeap, status,merchantId);
	}

	//查询某商户的打折商品
	@Override
	public List<GoodsVO> findByMerchantIdAndIsDiscountAndStatus(Long maxId,Long merchantId,
			Integer isDiscount,Integer status) {
		
		List<Goods> goodsList=goodsDao.findByMerchantIdAndIsDiscountAndStatus(maxId,merchantId, isDiscount, status);
		List<GoodsVO> goodsVOs=new ArrayList<GoodsVO>();
		
		for (Goods goods : goodsList) {
			
			GoodsVO goodsVO=new GoodsVO();
			goodsVO.setGoods(goods);
			goodsVOs.add(goodsVO);
		}
		
		return goodsVOs;
	}

	@Override
	public List<Goods> ajaxGoodsVO(Long marketid, Long categoryid,
			Long districtid, Integer isParentCategory, Integer status,
			Integer index, Integer offset) {
		StringBuffer sql = new StringBuffer();
		sql.append("select DISTINCT g.* from commodity_goods g LEFT JOIN t_merchant_merchant merchant ON merchant.id =g.merchant_id ");
		//过滤:分类
		if(categoryid!=-1){
			sql.append(" LEFT JOIN commodity_category c ON  c.id=g.category_id  ");
			sql.append(" LEFT JOIN t_merchant_market market ON market.id=merchant.market_id ");
		}
		//过滤:商圈
		if(districtid!=-1){
			sql.append(" LEFT JOIN t_merchant_business_district d ON  d.id= merchant.district_id ");
		}
		sql.append(" where g.status ="+status);
		sql.append(" and  merchant.market_id = "+marketid );
		if(categoryid!=-1){
			if(isParentCategory==1){
				sql.append(" and d.parent_id = "+categoryid);
			}else{
				sql.append(" and d.id = "+categoryid);
			}
		}
		if(districtid!=-1){
			sql.append(" and e.id = "+districtid);
		}
		sql.append(" and  g.id >"+index );
		sql.append(" order by g.id asc");
		sql.append(" limit "+offset);
		Query query = em.createNativeQuery(sql.toString(), Goods.class);
		@SuppressWarnings("unchecked")
		List<Goods> list = (List<Goods>) query.getResultList();
		return list;
	}

	@Override
	public List<Goods> ajaxHuiLife(Long marketId, Integer status, String name) {
		return goodsDao.findTop5ByStatusAndMerchantStatusAndMerchantMarketIdAndNameLikeOrderBySalesDesc(status , StatusEnum.NORMAL.getValue(), marketId , "%"+name+"%");
	}

	@Override
	public Page<Goods> getGoodsXTCApi(Integer sortno, Integer offset,Integer type,
			Goods goods) throws Exception {
		List<SearchFilter> filters = new ArrayList<SearchFilter>();
		 
		filters.add(new SearchFilter("id", SearchFilter.Operator.GT,sortno)); 
		 //商品上架状态
		filters.add(new SearchFilter("status", SearchFilter.Operator.EQ,GoodsStatusEnum.UP.getValue()));
		filters.add(new SearchFilter("merchant.type", SearchFilter.Operator.EQ,type)); 
//		if(goods!=null){
//			//商户ID
//			if(goods.getMerchant()!=null){
//			    filters.add(new SearchFilter("merchant.id", SearchFilter.Operator.EQ,goods.getMerchant().getId())); 
//			  
//			}  
//		
//		} 
		 
		return get(offset, null, 0L, filters, Goods.class);
	}
	
	//条件查询商品(主页面模糊查询商品)
	@Override
	public List<GoodsVO> findByStatusAndNameLike(Integer status, String name,
			Long marketId,Long Id) throws Exception {
		
			List<GoodsVO> list=new ArrayList<GoodsVO>();
			//查询商品
			List<Goods> goods= goodsDao.findByStatusAndNameLike(status,"%"+name+"%", marketId,Id);
			for (int i = 0; i < goods.size(); i++) {
				GoodsVO vo=new GoodsVO();
				vo.setGoods(goods.get(i));
				vo.setScore(commentService.getAvgScore(goods.get(i).getId()));
				list.add(vo);
			}
			
		return list;
	}


	
	//删除商品之前的图片
	public void deletePics(Long goodsid) throws Exception{
		List<GoodsPic> picsList = goodsPicService.findByPropertyName("goods.id", goodsid, GoodsPic.class);
		for (GoodsPic pic : picsList) {
			goodsPicService.delete(pic);
		}
	}

	//查询线下商品
	@Override
	public List<GoodsVO> getDownPag(Integer status, Long marketId,Integer Id)
			throws Exception {
		List<GoodsVO> list=new ArrayList<GoodsVO>();
		//查询商品
		List<Goods> goods=goodsDao.getDownPag(status,marketId,Id,XTCEnum.D.getValue());
		for (int i = 0; i < goods.size(); i++) {
			GoodsVO vo=new GoodsVO();
			vo.setGoods(goods.get(i));
			vo.setScore(commentService.getAvgScore(goods.get(i).getId()));
			list.add(vo);
		}
		return list;
	}

	@Override
	public Map<String,Object> getGoodsByCategoryId() {
//		//创建分页请求.
//				int pageNumber = request.getPage();
//				int pageSize = request.getRows();
//				String sortType = StringUtils.isEmpty(request.getSidx())?"id":request.getSidx();
//				String sortDirection = StringUtils.isEmpty(request.getSord())?"desc":request.getSord();
//				Direction direction = sortDirection.equals("desc")?Direction.DESC:Direction.ASC;
//				Sort sort = new Sort(direction, sortType);
//				PageRequest pageRequest = new PageRequest(pageNumber - 1, pageSize, sort);
//
//				//创建动态查询条件组合.
//				Collection<SearchFilter> filters = SearchFilter.parse(request);
//				//过滤:企业
//				if(Reflections.existsField("corp", clz)){
//					if(corpid!=1L){
//						filters.add(new SearchFilter("corp.id", Operator.EQ, corpid));
//					}
//				}
//				//过滤:状态
//				if(Reflections.existsField("status", clz)){
//					filters.add(new SearchFilter("status", Operator.NE, StatusEnum.DELETE.getValue()));
//				}
//				Specification<T> spec = DynamicSpecifications.bySearchFilter(filters, clz);
//				return baseRepository.findAll(spec, pageRequest);
		
		return null;
	}

	@Override
	public List<FloorGoodsVO> getGoodsAllForFloor(Integer status) throws Exception {
		List<Goods> goodList = goodsDao.findByStatus(status);
		return CommentToVo(goodList);
	}
	//分页查询商品列表
	public Map<String, Object> getGoods(int pageNumber, int pageSize,
			String sortType, String sortDirection, String name,
			String categoryId) {
		//创建分页请求.
		Direction direction = sortDirection.equals("desc")?Direction.DESC:Direction.ASC;
		Sort sort = new Sort(direction, sortType);
		PageRequest pageRequest = new PageRequest(pageNumber - 1, pageSize, sort);
		
		//创建动态查询条件组合.
		Collection<SearchFilter> filters = new ArrayList<SearchFilter>();
		Long cId=null;
		if(StringUtils.isNotBlank(categoryId)){cId = Long.valueOf(categoryId);}
		
		if(cId != null){
			filters.add(new SearchFilter("category.id", Operator.EQ, cId));
		}
		if(StringUtils.isNoneBlank(name)){
			filters.add(new SearchFilter("name", Operator.CN, name));
		}
		
		filters.add(new SearchFilter("status", Operator.EQ, 2));
		
		Specification<Goods> spec = DynamicSpecifications.bySearchFilter(filters, Goods.class);
		Page<Goods> page = goodsDao.findAll(spec, pageRequest);
		Long count = page.getTotalElements();
		List<Goods> selPro = page.getContent();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("count", count);//分页所需的分类总数
		map.put("list", selPro);//分页集合
		return map;
	}

	@Override
	public Map<String,Object> getGoodsPag(int pageNumber, int pageSize,
			String sortType, String sortDirection, Long categoryId) {
		//创建分页请求.
		Direction direction = sortDirection.equals("desc")?Direction.DESC:Direction.ASC;
		Sort sort = new Sort(direction, sortType);
		PageRequest pageRequest = new PageRequest(pageNumber - 1, pageSize, sort);
		
		//创建动态查询条件组合.
		Collection<SearchFilter> filters = new ArrayList<SearchFilter>();
		
		filters.add(new SearchFilter("status", Operator.EQ, StatusEnum.NORMAL.getValue()));
		filters.add(new SearchFilter("category.id", Operator.EQ, categoryId));
		
		Specification<Goods> spec = DynamicSpecifications.bySearchFilter(filters, Goods.class);
		Page page = goodsDao.findAll(spec, pageRequest);
		Long count = page.getTotalElements();
		List<Goods> selPro = page.getContent();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("count", count);//分页所需的分类总数
		map.put("list", selPro);//分页集合
		return map;
	}
	


	
	public List<FloorGoodsVO> CommentToVo(List<Goods> goodList){
		List<FloorGoodsVO> voList = new ArrayList<FloorGoodsVO>();
		for (Goods goods : goodList) {
			FloorGoodsVO vo = new FloorGoodsVO();
			vo.setId(goods.getId());
			vo.setName(goods.getName());
			vo.setPicurl(goods.getPicurl());
			/**得到分类*/
			Category cate = goods.getCategory().getPcategory();
			if(cate==null){
				vo.setParentId(goods.getCategory().getId());
				vo.setChildId(null);
			}else{
				vo.setParentId(cate.getId());
				vo.setChildId(goods.getCategory().getId());
			}
			voList.add(vo);
			
		}
		return voList;
	}

	//验证商品是否下架
	@Override
	public boolean checkIsDown(OrderPlat orderPlat) {
		
		if(orderPlat!=null && orderPlat.getOrderList().size()>0){
			//所有商户订单
			List<Order> orderList = orderPlat.getOrderList();
			for (Order order : orderList) {
				
				List<OrderItem> items = orderItemDao.findByOrderId(order.getId());
				for (OrderItem item : items) {
					if(item.getGoods().getStatus().intValue()==GoodsStatusEnum.DOWN.getValue()){
						return false;
					}
				}
			}
		}
		return true;
	}

	//验证购买的商品是否超过限额
	@Override
	public boolean checkPurRestrictions(OrderPlat orderPlat) {
		if(orderPlat!=null && orderPlat.getOrderList().size()>0){
			//所有商户订单
			List<Order> orderList = orderPlat.getOrderList();
			for (Order order : orderList) {
				
				List<OrderItem> items = orderItemDao.findByOrderId(order.getId());
				for (OrderItem item : items) {
					if(item.getGoods().getIsPurRestrictions()==YesOrNoEnum.YES.getValue()){
						//根据会员和商品ID查询限额数量
						int amount=purrestrictionsService.findByMemberIdAndGoodsId(orderPlat.getMember().getId(), item.getGoods().getId());
						//验证购买的商品是否超过限额
						boolean isPur=purrestrictionsService.checkPurRestrictions(item.getGoods(), amount+item.getAmount());
						if(!isPur){
							return false;
						}
						
					}
				}
			}
		}
		return true;
	}

	
	
	
}
